package de.baumann.browser.present

import de.baumann.browser.api.OdinObserver
import de.baumann.browser.api.net.vo.Card
import de.baumann.browser.api.net.vo.PayParam
import de.baumann.browser.base.BasePresenter
import de.baumann.browser.iview.ICardDetailView
import de.baumann.browser.model.CardModel
import de.baumann.browser.rx.RxSchedulers
import de.baumann.browser.utils.web3j.TokenUtil
import io.reactivex.Observable
import io.reactivex.ObservableOnSubscribe
import io.reactivex.Observer
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import io.reactivex.schedulers.Schedulers
import java.sql.RowId
import java.util.*

class CardDetailPresenter : BasePresenter<ICardDetailView>() {
    private lateinit var card: Card
    fun getCardData() {
        card = view.getCard()
        view.setCardName(card.cardName)
        view.setCardPrice(card.cardPrice + "ODIN")
        view.setCardType(card.cardType)
        view.setCardPower(card.cardPower!!)
        view.setCardPowerDescs(card.powerDescs!!)
    }


    fun transfer(fromAddress: String, privateKey: String) {
        Observable.create(ObservableOnSubscribe<String> { emitter ->
            try {
                val hash = TokenUtil.transferETH(fromAddress,
                        privateKey,
                        view!!.getToAddress(),
                        view!!.getAmount(),
                        0)
                if (hash == null) {
                    emitter.onError(Throwable("转账失败"))
                } else {
                    emitter.onNext(hash)
                }
            } catch (e: Exception) {
                e.printStackTrace()
                emitter.onError(e)
            }
        }).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(object : Observer<String> {
                    override fun onComplete() {
                    }

                    override fun onSubscribe(d: Disposable) {
                    }

                    override fun onNext(t: String) {
                        if (view != null) {
                            view!!.transferSuccess(t)
                        }
                    }

                    override fun onError(e: Throwable) {
                        if (view != null && e.message != null) {
                            view!!.onError(e.message);
                        }
                    }
                })
    }


    fun callAfterBuy(cardId: String, hash: String) {
        CardModel().callAfterBuy(cardId, hash)
                .compose(RxSchedulers.ioMain())
                .subscribe(object : OdinObserver<Any>() {
                    override fun onSuccess(data: Any?) {
                        if (view != null) {
                            view!!.buySuccess()
                        }
                    }
                })
    }

}